var Koa = require('koa');
const route = require('koa-route');
var cors = require('koa-cors');
var app = new Koa();
app.use(cors());
let qk = require('./serverUpdataTask')


const updataTask = async ctx => {
  ctx.response.type = 'application/json';
  let cookie = ctx.request.query.cookie
  let userName = ctx.request.query.userName
  console.log('>>>updataTask')
  console.log(cookie,userName)
  if (cookie) {
    console.log(cookie)
    let data = await getTask(userName, cookie)
    ctx.response.body = JSON.stringify(data);
  } else {
    ctx.response.body = JSON.stringify({
      message: 'cookie为空',
      code: 4001
    });
  }

};

const autoApplyTask = async ctx => {
  try {
    let cookie = ctx.request.query.cookie
    let userName = ctx.request.query.userName
    let type = parseInt(ctx.request.query.type) || 0
    if (cookie) {
      let data = await applyTask(userName, cookie, type)
      ctx.response.body = data
    } else {
      ctx.response.body = {
        message: 'cookie为空',
        code: 4001
      }
    }
  } catch (err) {
    ctx.response.body = {
      message: err.message,
      success:false
    }
  }
}

function applyTask(userName, cookie, type) {
  return new Promise((resolve, reject) => {
    try {
      qk.applyTask(userName, cookie, type, res => {
        resolve(res)
      })
    } catch (err) {
      reject(err)
    }
  })
}

function getTask(userName, cookie) {
  return new Promise((resolve, reject) => {
    try {
      qk.updataTask(userName, cookie, res => {
        resolve(res)
      })
    } catch (err) {
      reject(err)
    }
  })
}

app.use(route.get('/updataTask', updataTask));
app.use(route.get('/autoApplyTask', autoApplyTask))
app.listen(3000);
